import { useState } from 'react';
import { View, Text } from 'react-native';
import Button from './Button';
import { myColors } from '../styles/Colors';
import { Styles } from '../styles/GlobalStyles';


export default function MyKeyBoard() {
    // 存储当前输入的第一个数字或中间结果
    const [firstNumber, setFirstNumber] = useState<string>('');
    // 存储上一次输入的数字，用于运算
    const [secondNumber, setSecondNumber] = useState<string>('');
    // 存储计算结果
    const [result, setResult] = useState<number | null>(null);
    // 存储当前选择的运算符号（+、-、*、/ 等）
    const [operation, setOperation] = useState<string>('');

    // 处理数字按键点击，拼接数字到 firstNumber，限制长度小于 10
    const handleNumberPress = (buttonValue: string) => {
        if (firstNumber.length < 10) {
            setFirstNumber(firstNumber + buttonValue);
        }
    };

    // 处理运算符号按键点击，准备进行运算
    const handleOperationPress = (buttonValue: string) => {
        // 如果有计算结果（result 不为 null），就把 result 作为新的 secondNumber
        if (result !== null) {
            setSecondNumber(result.toString());
        } else {
            // 没有结果时，仍用原来的 firstNumber
            setSecondNumber(firstNumber);
        }
        // 记录当前运算符号
        setOperation(buttonValue);
        // 清空 firstNumber，准备输入下一个数字
        setFirstNumber('');
    };

    // 处理清空操作，重置所有状态
    const handleClear = () => {
        setFirstNumber('');
        setSecondNumber('');
        setResult(null);
        setOperation('');
    };

    // 处理正负号切换，改变 firstNumber 的正负
    const handleToggleSign = () => {
        if (firstNumber) {
            const num = parseFloat(firstNumber);
            setFirstNumber((-num).toString());
        }
    };

    // 处理百分比运算，将 firstNumber 转换为百分比数值
    const handlePercent = () => {
        if (firstNumber) {
            const num = parseFloat(firstNumber);
            setFirstNumber((num / 100).toString());
        }
    };

    // 执行计算逻辑，根据 operation 进行相应运算
    const getResult = () => {
        // 若缺少运算符号、参与运算的数字，直接返回
        if (!operation || !secondNumber || !firstNumber) return;
        let computedResult: number;
        switch (operation) {
            case '+':
                computedResult = parseFloat(secondNumber) + parseFloat(firstNumber);
                break;
            case '-':
                computedResult = parseFloat(secondNumber) - parseFloat(firstNumber);
                break;
            case '*':
                computedResult = parseFloat(secondNumber) * parseFloat(firstNumber);
                break;
            case '/':
                // 除数不能为 0，若为 0 弹出提示并返回
                if (parseFloat(firstNumber) === 0) {
                    alert('除数不能为 0');
                    return;
                }
                computedResult = parseFloat(secondNumber) / parseFloat(firstNumber);
                break;
            default:
                return;
        }
        // 保留计算结果作为下一次计算的起点
        setSecondNumber(computedResult.toString());
        setFirstNumber('');
        setResult(computedResult);
    };

    // 控制第一个数字/结果的显示逻辑，根据不同状态显示不同内容和样式
    const firstNumberDisplay = () => {
        // 有结果且 firstNumber 为空时，显示结果，根据结果大小调整样式
        if (result !== null && firstNumber === '') {
            return <Text style={result < 99999 ? [Styles.screenFirstNumber, { color: myColors.result }] : [Styles.screenFirstNumber, { fontSize: 50, color: myColors.result }]}>{result?.toString()}</Text>
        }
        // firstNumber 存在且长度小于 6，正常显示
        if (firstNumber && firstNumber.length < 6) {
            return <Text style={Styles.screenFirstNumber}>{firstNumber}</Text>
        }
        // firstNumber 为空时显示 0
        if (firstNumber === '') {
            return <Text style={Styles.screenFirstNumber}>{'0'}</Text>
        }
        // firstNumber 长度在 5 到 8 之间，调整字体大小显示
        if (firstNumber.length > 5 && firstNumber.length < 8) {
            return (
                <Text style={[Styles.screenFirstNumber, { fontSize: 70 }]}>{firstNumber}</Text>
            )
        }
        // firstNumber 长度大于 7，调整字体大小显示
        if (firstNumber.length > 7) {
            return (
                <Text style={[Styles.screenFirstNumber, { fontSize: 50 }]}>{firstNumber}</Text>
            )
        }
    };


    return (
        // 计算器底部布局容器
        <View style={Styles.viewBottom}>
            <View style={{
                height: 120,
                width: '90%',
                // 内容靠下对齐
                justifyContent: 'flex-end',
                alignSelf: 'center'
            }}>
                {/* 显示上一次数字和运算符号 */}
                <Text style={Styles.screenSecondNumber}>
                    {secondNumber}
                    <Text style={{ color: 'purple', fontSize: 50, fontWeight: '500' }}>{operation}</Text>
                </Text>
                {/* 显示当前输入数字或结果 */}
                {firstNumberDisplay()}
            </View>
            {/* 以下是各排按钮，分别绑定对应的处理函数 */}
            <View style={Styles.row}>
                <Button title='C' isGray onPress={handleClear} />
                <Button title='+/-' isGray onPress={handleToggleSign} />
                <Button title='%' isGray onPress={handlePercent} />
                <Button title='÷' isBlue onPress={() => handleOperationPress('/')} />
            </View>
            <View style={Styles.row}>
                <Button title='7' onPress={() => handleNumberPress('7')} />
                <Button title='8' onPress={() => handleNumberPress('8')} />
                <Button title='9' onPress={() => handleNumberPress('9')} />
                <Button title='×' isBlue onPress={() => handleOperationPress('*')} />
            </View>
            <View style={Styles.row}>
                <Button title='4' onPress={() => handleNumberPress('4')} />
                <Button title='5' onPress={() => handleNumberPress('5')} />
                <Button title='6' onPress={() => handleNumberPress('6')} />
                <Button title='-' isBlue onPress={() => handleOperationPress('-')} />
            </View>
            <View style={Styles.row}>
                <Button title='1' onPress={() => handleNumberPress('1')} />
                <Button title='2' onPress={() => handleNumberPress('2')} />
                <Button title='3' onPress={() => handleNumberPress('3')} />
                <Button title='+' isBlue onPress={() => handleOperationPress('+')} />
            </View>
            <View style={Styles.row}>
                <Button title='.' onPress={() => handleNumberPress('.')} />
                <Button title='0' onPress={() => handleNumberPress('0')} />
                <Button title='🔙' onPress={() => setFirstNumber(firstNumber.slice(0, -1))} />
                <Button title='=' isBlue onPress={() => getResult()} />
            </View>
        </View>
    )
}
